package qin.service.Impl;

import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

import qin.dao.BookDao;
import qin.entity.Book;
import qin.entity.R;
import qin.service.BookService;
import qin.util.InvocationHandlerImpl;

/**
 * book服务具体实现
 * @author 小行星
 *
 */
public class BookServiceImpl implements BookService {
	private static BookService bookService;
	private static BookDao bookDao;
	private static final Object lock = new Object();
	
	private BookServiceImpl() {}
	
	public static BookService build() {
		if(bookService == null) {
			synchronized(lock) {
				if(bookService == null) {
					bookDao = BookDao.build();
					bookService = new BookServiceImpl();
					InvocationHandler handler = new InvocationHandlerImpl(bookService);
					for (Annotation annotation : bookService.getClass().getAnnotations()) {
						System.out.println(annotation);
					}
					ClassLoader loader = bookService.getClass().getClassLoader();
					Class<?>[] interfaces = bookService.getClass().getInterfaces();
					bookService = (BookService)Proxy.newProxyInstance(loader, interfaces, handler);
				}
			}
		}
		
		return bookService;
	}

	@Override
	public R<?> addBook(Book book) {
		int index = bookDao.getBookIndexByNumber(book.getNumber());
		if(-1 != index) return R.no("书号已存在！", null);
		bookDao.addBook(book);
		return R.ok(null, null);
	}

	@Override
	public R<?> updateBook(String number, Book book) {
		int index = bookDao.getBookIndexByNumber(number);
		if(-1 == index) return R.no("要修改的书不存在！", null);
		bookDao.updateBook(index, book);
		return R.ok(null, null);
	}

	@Override
	public R<?> deleteBook(String number) {
		int index = bookDao.getBookIndexByNumber(number);
		if(-1 == index) return R.no("要删除的书不存在！", null);
		bookDao.deleteBook(index);
		return R.ok(null, null);
	}

	@Override
	public R<List<Book>> getBooks() {
		List<Book> books = bookDao.getBooks().stream().sorted(Comparator.comparing(Book::getNumber)).collect(Collectors.toList());
		return R.ok(null, books);
	}

	@Override
	public R<Book> getBookByNumber(String number) {
		Book book = bookDao.getBookByNumber(number);
		if(null == book) return R.no("要修改的书不存在！", null);
		return R.ok(null, book);
	}

	@Override
	public R<List<Book>> getBooksByAuthor(String author) {
		List<Book> books = bookDao.getBookByAuthor(author).stream().sorted(Comparator.comparing(Book::getNumber)).collect(Collectors.toList());
		return R.ok(null, books);
	}

	@Override
	public R<List<Book>> getBooksByPress(String press) {
		List<Book> books = bookDao.getBookByPress(press).stream().sorted(Comparator.comparing(Book::getNumber)).collect(Collectors.toList());
		return R.ok(null, books);
	}
}
